<template>
  <div class="flex_bw_start" style="height: 100%">
    <div class="big_left">
      <div class="card_title" style="
          display: flex;
          justify-content: space-between;
          flex-direction: row;
          align-items: center;
        ">
        <div class="card_title_text">产品SPU</div>
        <div>
          <el-icon style="margin-right: 30px">
            <Search class="icon_hover" />
          </el-icon>
          <!-- <el-icon @click="handleAddGroup">
                        <Plus class="icon_hover" />
                    </el-icon> -->
        </div>
      </div>

      <div class="full-height-card" style="overflow-y: scroll">
        <div class="button-container"></div>
        <el-tree ref="treeRef" highlight-current class="full-height-tree" 
          :data="Array.isArray(departmentTree) ? departmentTree : []" node-key="id" :props="treeProps"
          :current-node-key="departmentTree?.[0]?.id" accordion
          @node-click="handleNodeClick">
          <template #default="scope">
            <div class="custom-tree-node">
              <span :class="{ 'disabled-node': scope.node.data.status === 0 }">{{
                scope.node.label
              }}</span>

              <!-- <span class="operation-icons">
                                <el-dropdown trigger="click" @command="handleCommand">
                                    <el-icon class="custom-icon">
                                        <Tools color="#172B4D" />
                                    </el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item
                                                :command="{ type: 'edit', data: scope.node.data }">编辑</el-dropdown-item>
                                            <el-dropdown-item
                                                :command="{ type: 'delete', data: scope.node.data }">删除</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
</el-dropdown>
</span> -->
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <div style="width: calc(100% - 260px)">
      <div class="page-box" style="margin-top: 50px">
        <div class="page-search">
          <div class="search-box" :style="{ height: IsHeight }">
            <el-input v-model="search" placeholder="产品名称/产品编码" @input="getAlltabeData"
              style="width: 200px; margin-right: 20px; margin-bottom: 10px" />

            <div class="search-box-item flex_center_center" style="transform: translateY(-5px)">
              <span class="margin-right-10">显示:</span>
              <el-button :color="statusData === '1' ? '#172B4D' : ''" @click="handleStatusFilter('1')">
                已上架
              </el-button>
              <el-button :color="statusData === '0' ? '#172B4D' : ''" @click="handleStatusFilter('0')">
                已下架
              </el-button>
            </div>
          </div>

          <div class="search-btn" style="padding-right: 30px">
            <div class="btn_item" @click="handleClickHeight">
              <img class="btn_img" src="@/assets/sx.png" alt="" /> <span> 高级筛选 </span>
            </div>
          </div>
        </div>
        <div class="search-btn-right" style="top: -50px">
          <el-button color="#626aef" type="primary" @click="handleSave('add', { id: undefined })">
            新增产品
          </el-button>
        </div>
      </div>

      <div class="table-box">
        <el-table :data="tabeData" style="width: 100%" v-loading="loading" border>
          <el-table-column align="center" prop="name" label="产品名称" />
          <el-table-column align="center" prop="no" label="产品编码" />
          <el-table-column align="center" prop="specification" label="规格型号" />
          <el-table-column align="center" prop="measure_unit_name" label="单位" />
          <el-table-column align="center" prop="spu_name" label="spu" />
          <el-table-column align="center" prop="price" label="单价(元)" />
          <!-- <el-table-column align="center" prop="price" label="市场价" /> -->
          <el-table-column align="center" prop="status_text" label="状态">
            <template #default="scope">
              <el-tag v-if="scope.row.status == 1" type="success">已上架</el-tag>
              <el-tag v-else type="danger">已下架</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="remark" label="备注" /> -->
          <!-- <el-table-column align="center" prop="img" label="产品图片">
                        <template #default="scope">
                            <img v-if="scope.row.img && scope.row.img.length" :src="scope.row.img[0]" alt="产品图片" style="width: 40px; height: 40px; object-fit: cover;" />
                        </template>
                    </el-table-column> -->
          <el-table-column align="center" prop="creator_name" label="创建人" />
          <el-table-column align="center" prop="created_at" label="创建时间" width="180" />
          <el-table-column fixed="right" label="操作" min-width="150" prop="id" align="center">
            <template #default="scope">
              <div class="btn-box">
                <el-button plain size="small" type="primary" @click="handleSave('edit', scope.row)">
                  编辑
                </el-button>
                <el-button plain size="small" type="warning" v-if="scope.row.status == 1"
                  @click="handleStatusChange(scope.row)">下架</el-button>
                <el-button plain size="small" type="success" v-else
                  @click="handleStatusChange(scope.row)">上架</el-button>
                <el-button plain size="small" type="danger" @click="handleDeleteProduct(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <Pagination class="pagination" @pageSize="pageSize" @getPage="getPage" :page="pageData.page"
        :page-size="pageData.pageSize" :total="total" />
    </div>
  </div>

  <Dialog :departmentTree="departmentTree" :TreeId="TreeId" v-model:dialogVisible="isShow" :dialogType="dialogType"
    :dialogRow="dialogRow" @submit="handleDialogSubmit" @cancel="handleDialogCancel" />
  <AddDialog v-model:dialogVisible="addDialogVisible" :dialogType="dialogType" :dialogRow="addDialogRow"
    @submit="handleDialogSubmit" @cancel="handleDialogCancel" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from "vue";
import Pagination from "@/components/Pagination.vue";
import AddDialog from "./components/addDialog.vue";
import api from "@/api";
import Dialog from "./components/dialog.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { ElTree } from "element-plus";
import { dataType, ApiResponse } from "@/utils/publicType";

interface TreeData {
  id: number;
  name: string;
  parent_id: number;
}

// 模拟部门数据
const departmentTree = ref<TreeData[]>([]);

let IsHeight = ref<number | string>(0);
const search = ref<string>("");
const pageData = ref({
  pageSize: 10,
  page: 1,
  house_type: "",
  category: "",
  keywords: "",
});

const isShow = ref<boolean>(false);

const treeProps = {
  children: "children",
  label: "name",
};

// 树组件引用
const treeRef = ref<InstanceType<typeof ElTree>>();

// 节点点击处理
const handleNodeClick = (data: TreeData) => {
  console.log("点击节点:", data);
  TreeId.value = data.id;
  console.log("更新选中分组ID:", TreeId.value);
  getAlltabeData();
  if (treeRef.value) {
    // 设置当前选中节点
    treeRef.value.setCurrentKey(data.id);
  }
};

// 节点编辑处理
const handleEdit = (data: TreeData) => {
  dialogType.value = "edit";
  addDialogRow.value = { ...data };
  addDialogVisible.value = true;
};

// 侦听动态分页
watch(
  () => {
    return pageData.value;
  },
  () => {
    getAlltabeData();
  },
  { deep: true }
);

let nub = ref<number>(0);
const handleClickHeight = (): void => {
  nub.value++;
  if (nub.value % 2 == 1) {
    IsHeight.value = "40px";
  } else {
    IsHeight.value = "0px";
  }
};

const pageSize = (e: number) => {
  pageData.value.pageSize = e;
};
const getPage = (e: number) => {
  pageData.value.page = e;
};
onMounted(async () => {
  await getGroupTree();
  await getAlltabeData();
});

let TreeId = ref<number>(0);

// 获取产品分组树
const getGroupTree = async () => {
  try {
    const res: ApiResponse<TreeData> = await api.productbasics.getproductList({ page: 'all' });
    if (res.code == 200) {
      departmentTree.value = res.data as TreeData[];
      console.log("获取产品分组树成功:", departmentTree.value);
      if (departmentTree.value && departmentTree.value.length > 0) {
        TreeId.value = departmentTree.value[0].id;

        // 确保树加载完成后选中第一个节点
        // nextTick(() => {
        //     if (treeRef.value) {
        //         treeRef.value.setCurrentKey(TreeId.value);
        //     }
        // });
      } else {
        console.warn("产品分组树为空");
      }
    } else {
      console.error("获取产品分组树失败:", res.message);
    }
  } catch (error) {
    console.error("获取产品分组树异常:", error);
  }
};
interface tabeData {
  id?: number;
  no?: string;
  name?: string;
  group_id?: number;
  price?: string;
  cost_price?: string;
  measure_unit_id?: number;
  specification?: string;
  status?: number;
  created_at?: string;
  creator_name?: string;
  measure_unit_name?: string;
  spu_name?: string;
  status_text?: string;
}
const total = ref<number>(0);
const tabeData = ref<tabeData[]>([]);
// 获取门店列表
const getAlltabeData = async () => {
  let res = await api.product.product_list({
    page: pageData.value.page,
    pageSize: pageData.value.pageSize,
    keywords: search.value,
    spu_id: TreeId.value || "",
    status: statusData.value,
  });
  if (res.code == 200) {
    tabeData.value = res.data.data;
    total.value = res.data.pager.total_records;
  }
  // setTimeout(() => {
  //     loading.value = false;
  // }, 10);
};

const loading = ref<boolean>(false);

let dialogType = ref<string>("");
let dialogRow = ref<tabeData>();
const handleAddGroup = () => {
  dialogType.value = "add";
  addDialogVisible.value = true;
};
const handleSave = async (type: string, row: tabeData) => {
  // 确保已加载产品分组数据
  if (departmentTree.value.length === 0) {
    await getGroupTree();
  }
  if (type == "add") {
    dialogRow.value = {};
  } else {
    //调用详情product_detail
    let res = await api.product.product_detail({ id: row.id });
    if (res.code == 200) {
      dialogRow.value = res.data || {};
    }
  }

  dialogType.value = type;
  isShow.value = true;
};

let addDialogVisible = ref<boolean>(false);
let addDialogRow = ref<{}>({});
const handleDialogSubmit = () => {
  getAlltabeData();
  // getGroupTree();
};

const handleDialogCancel = () => {
  getGroupTree();
  getAlltabeData();
};

const handleCommand = (command: any) => {
  if (command.type === "edit") {
    handleEdit(command.data);
  } else if (command.type === "delete") {
    ElMessageBox.confirm(`确定要删除分组 "${command.data.name}" 吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        handleDeleteGroup(command.data);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });
  }
};

// 处理删除分组
const handleDeleteGroup = async (data: TreeData) => {
  const res: dataType = await api.product.product_group_delete({
    id: data.id,
  });
  if (res.code == 200) {
    ElMessage.success(res.message);
    getGroupTree();
  }
};

// 处理产品上下架状态变更
const handleStatusChange = (row: tabeData) => {
  const action = row.status === 1 ? "下架" : "上架";
  ElMessageBox.confirm(`确定要${action}产品 "${row.name}" 吗？`, `${action}确认`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        const res = await api.product.product_status({
          id: row.id,
        });
        if (res.code === 200) {
          ElMessage.success(res.message || `${action}成功`);
          getAlltabeData(); // 刷新列表
        } else {
          ElMessage.error(res.message || `${action}失败`);
        }
      } catch (error) {
        console.error(`产品${action}异常:`, error);
        ElMessage.error(`${action}失败，请稍后重试`);
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消${action}`,
      });
    });
};

// 处理产品删除
const handleDeleteProduct = (row: tabeData) => {
  ElMessageBox.confirm(`确定要删除产品 "${row.name}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        const res = await api.product.product_delete({
          ids: [row.id],
        });
        if (res.code === 200) {
          ElMessage.success(res.message || "删除成功");
          getAlltabeData(); // 刷新列表
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("产品删除异常:", error);
        // ElMessage.error('删除失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

let statusData = ref<string | null>("");
// 处理状态筛选
const handleStatusFilter = (status: string) => {
  if (statusData.value == "") {
    statusData.value = status;
  } else if (statusData.value != "" && status == statusData.value) {
    statusData.value = "";
  } else {
    statusData.value = status;
  }

  getAlltabeData();
};
</script>

<style lang="scss" scoped>
::v-deep .el-tree {
  --el-tree-node-content-height: 34px;
}

.icon_hover {
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    color: #172b4d;
    transform: scale(1.2);
  }
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #7962ef15;
  color: var(--el-color-btn);
}

.full-height-card {
  height: 750px;
  background-color: #fff;
  padding: 10px 8px;
  box-sizing: border-box;
  overflow-y: auto;
}

.card_title {
  padding: 20px 16px 10px 16px;
  margin-bottom: 10px;

  .card_title_text {
    text-shadow: 2px 2px 6px #383737a3;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
  height: 34px;
  line-height: 34px;
}

.disabled-node {
  color: #c0c4cc;
}

.operation-icons {
  display: none;
  margin-left: 10px;
}

.el-tree-node__content:hover .operation-icons {
  display: inline-flex;
  gap: 8px;
}

.custom-icon {
  font-size: 16px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.custom-icon:hover {
  color: #409eff;
  transform: scale(1.1);
}

.full-height-tree {
  flex: 1;
  overflow: auto;
}

.big_left {
  width: 240px;
  border-radius: 6px;
  padding: 0 10px;
  box-sizing: border-box;
  height: 100%;
  padding-bottom: 20px;
  background-color: rgb(245, 248, 253);
}

.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

// 输入框样式
::v-deep .el-input__wrapper {
  background-color: rgba(250, 252, 251, 1);
}

//表格样式

::v-deep .el-table {
  --el-table-header-bg-color: rgba(235, 236, 240, 1);
}

::v-deep .el-table thead {
  color: #444;
}

//分页样式
.pagination {
  width: calc(100% - 300px);
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding-top: 10px;
  border-top: 1px solid #98989848;
}

::v-deep .el-pagination.is-background .el-pager li.is-active {
  background-color: #000 !important;
}
</style>
